<template>
	<view class="content">
		<u-navbar class="head-index" :fixed="false" :safeAreaInsetTop="true" bgColor="#51d0d0" titleStyle="color:#fff"
			:autoBack="true" leftIconColor="#fff" title="设置"></u-navbar>

		<view class="CellBox">

			<u-cell-group :border="false">
				<u-cell :border="false" title="清理缓存" @click="clear">
					<view slot="value" class="x-f">
						<text style="color: #da1616;font-size: 13px;">{{fileSizeString}}</text>
						<uni-icons v-show="fileSizeString" color="#da1616" type="trash" size="18"></uni-icons>
					</view>
				</u-cell>
				<u-cell :border="false" title="安全设置" @click="ToticketPage" isLink></u-cell>
			</u-cell-group>


			<u-cell-group :border="false" style="margin-top: 20px;">
				<u-cell :border="false" title="系统权限" @click="OpenManage" isLink></u-cell>
				<u-cell :border="false" title="系统信息" @click="OpenSystemInfo" isLink></u-cell>
				<u-cell @click="openWebInBrowser(1)" :border="false" title="用户隐私协议" isLink></u-cell>
				<u-cell @click="openWebInBrowser(2)" :border="false" title="用户隐私政策" isLink></u-cell>
				<!-- <u-cell :border="false" title="关于我们"></u-cell>
				<u-cell :border="false" title="反馈与建议"></u-cell> -->
			</u-cell-group>


			<u-cell-group :border="false" style="margin-top: 20px;">
				<u-cell :border="false" title="版本介绍">
					<view slot="value">
						<text style="color: #999;font-size: 13px;">当前版本：{{version}}</text>
					</view>
				</u-cell>
				<u-cell :border="false" title="检查更新" @click="GetUpdate"></u-cell>
				<!-- <u-cell :border="false" title="退出/注销" @click="logout" isLink>
					<view slot="right-icon" class="x-ec">
						<uni-icons fontFamily="CustomFontPlatform" color="#ff694f" :size="20"
							style="margin-right:6px;">{{$utils.toUniCode('&#xe614;')}}</uni-icons>

						<u-icon name="arrow-right" color="info" size="16"></u-icon>
					</view>
				</u-cell> -->


			</u-cell-group>

			<!-- 退出登录 -->
			<!-- <view class="LoginOutBox">
				<button @click="LoginOut">退出</button>
			</view> -->

			<!-- 注销账号 -->
			<view class="logoutBox">
				<button @click="logout">退出/注销</button>
			</view>

		</view>


		<!-- 注销 -->
		<u-popup :show="popup_logout" mode="center" :closeOnClickOverlay="false" :round="4" @close="closePopup">
			<view class="popup-content">

				<view class="popup-content_close x-c" @click="closePopup">
					<uni-icons type="closeempty" color="#999" size="14"></uni-icons>
				</view>

				<view class="x-c title">
					<text>账号退出/注销</text>
				</view>

				<view class="popup-content_desc">
					<text>温馨提示：注销汇创云平台账号后，该企业代号下所有绑定的设备将禁止使用，汇创云平台数据将被全部清空，且无法恢复；仅退出登录，不会清除数据，请谨慎操作。</text>
				</view>

				<view class="check x-f">
					<checkbox-group @change="checkboxChange" style="width: fit-content;">
						<checkbox class="CheckBox" :checked="agree" color="#fff" activeBackgroundColor="#51d0d0"
							activeBorderColor="#51d0d0">
							<view style="margin-left: 6px;">
								<text>同意</text>
							</view>
						</checkbox>
					</checkbox-group>
					<view>
						<text style="color: #51d0d0;" @click="openWebInBrowser(-1)">《汇创云平台账号注销协议》</text>
					</view>
				</view>


				<view class="btnBox x-ac">
					<u-button type="primary" text="仅退出登录" @click="SubmitLoginOut"></u-button>

					<u-button :disabled="!agree" :type="agree ? 'error' : ''" text="确认注销"
						@click="startLogout"></u-button>
				</view>

			</view>
		</u-popup>

		<m-loading :text="loadingText" :showClose="showClose" v-model="showMLoading" @close="closeLoading"></m-loading>

	</view>
</template>

<script>
	// 更新APP用的
	// #ifdef APP-PLUS
	import MAPPUpdate from '@/uni_modules/mc-ui/components/m-app-update/js_sdk/appUpdate.js';
	// #endif

	import UseSqlite from '@/uni_modules/mc-ui/components/m-sqlite/js_sdk/sqlite-use.js';
	var UseSqliteFun = UseSqlite;
	export default {
		data() {
			return {
				loadingText: '正在处理...',
				showClose: true,
				showMLoading: false,
				popup_logout: false,
				agree: false, // 是否同意注销协议
				logoutTime: 5, // 注销倒计时
				version: null, // 本机版本号
				fileSizeString: '',
				timer: null,
			}
		},
		onReady() {
			// 需要在onReady中设置规则
			// this.$refs.baseForm.setRules(this.rules)
		},
		onLoad() {
			// 获取本机版本号
			this.version = plus.runtime.version;
			// 获取缓存数据
			this.formatSize();
		},
		watch: {
			showMLoading: {
				handler(nVal) {
					if (nVal) {
						// 开启销毁，触发销毁加载事件，保留终止能力

						this.openTimeOut();
					}
				}
			}
		},
		onBackPress(options) { // 监听页面返回
			if (!this.showClose) {
				return true
			} else {
				clearInterval(this.timeOutTimer);
				return false
			};
		},
		methods: {
			openTimeOut() {
				let that = this;
				that.timeOutTimer = setInterval(() => {
					that.logoutTime--;

					if (that.logoutTime <= 1) {
						that.loadingText = '正在申请注销...';
						that.showClose = false;
					} else {
						that.loadingText = '正在处理...';
						that.showClose = true;
					}

					if (that.logoutTime == 0) {
						clearInterval(that.timeOutTimer);
						that.SubmitLogout();
					}
				}, 1000);
			},
			closePopup() {
				// this.$refs.popup_logout.close()
				this.popup_logout = false;
				this.agree = false;
			},
			closeLoading() {
				clearInterval(this.timeOutTimer);
				this.showMLoading = false;
				this.closePopup();
			},
			startLogout() {
				this.showMLoading = true
				this.closePopup();
			},
			async SubmitLogout() { // 确认注销

				try {
					// 清除缓存  
					await new Promise((resolve, reject) => {
						plus.cache.clear(function(error) {
							if (error) {
								reject(error);
							} else {
								uni.clearStorageSync(); // 同步清理本地数据缓存。  
								resolve();
							}
						});
					});

					await UseSqliteFun.deleteSql();

					// 隐藏加载提示  
					this.$utils.hideLoading();

					// 等待2秒后重启应用  
					await new Promise(resolve => setTimeout(resolve, 1000));
					plus.runtime.restart();

				} catch (error) {
					// 错误处理  
					console.error('注销过程中发生错误:', error);
					this.$utils.hideLoading();
					this.$utils.showError('注销失败');
				}
			},
			logout() {
				// this.$refs.popup_logout.open()
				this.popup_logout = true;
			},
			checkboxChange(data) { // 注销是否同意
				var that = this;
				if (data.target.value.length) {
					that.agree = true;
				} else {
					that.agree = false;
				};
			},
			openWebInBrowser(id) { // 打开外链
				// #ifdef APP-PLUS  

				switch (id) {
					case 1: // 用户协议
						plus.runtime.openWeb('http://mes.hzyc.org.cn:20050/download/html/汇创云平台用户协议.html')
						// plus.runtime.openURL('http://mes.hzyc.org.cn:20050/download/html/汇创云平台用户协议.html');
						break;
					case 2: // 隐私政策
						plus.runtime.openWeb('http://mes.hzyc.org.cn:20050/download/html/汇创云平台隐私政策.html')
						// plus.runtime.openURL('http://mes.hzyc.org.cn:20050/download/html/汇创云平台隐私政策.html');
						break;
					case -1: // 注销协议
						plus.runtime.openWeb('http://hzyc.fld2018.com/download/app/APP_Init/汇创云平台注销协议.html')
						break;
					default:
						break;
				}
				// #endif  
			},
			ToticketPage() { // 打开ticket目录下的文件
				uni.navigateTo({
					url: '/pages/mine/SettingBox/SetSafety',
					fail(error) {
						console.log(error)
					}
				})

			},
			formatSize() { // 获取缓存
				let that = this;

				this.$utils.formatSize((ret => {
					that.fileSizeString = ret;
				}))
			},
			clear() { // 清除缓存
				let that = this
				uni.showModal({
					title: '清除缓存',
					content: '清除后会同时清理历史连接设备',
					confirmText: '立即清理',
					confirmColor: '#ff0707',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
							that.clearCache()

						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			// 清理缓存
			clearCache() {
				let that = this;
				UseSqliteFun.deleteSql();
				this.$utils.clearCache(that.fileSizeString, (ret) => {
					uni.clearStorageSync(); // 同步清理本地数据缓存。
					that.formatSize(); // 重新计算缓存

					setTimeout(() => {
						// 直接重启APP 直接让vuex的数据初始化，很方便
						plus.runtime.restart();
					}, 2000);
				});
			},
			OpenManage() { // 打开应用信息
				uni.openAppAuthorizeSetting({
					success(res) {
						console.log(res)
					}
				});
			},
			OpenSystemInfo() { // 获取软件系统信息
				uni.navigateTo({
					url: '/pages/mine/SettingBox/systemInfo'
				})
			},
			SubmitLoginOut() {
				// 清除一些需要重置的缓存

				this.$store.state.systemConfig.msgConfig.activeCtx.hide();

				this.$store.commit('ChangeAndSetStateData', {
					Name1: 'systemConfig.isLogin',
					data: false,
				});

				this.$store.commit('ChangeAndSetStateData', {
					Name1: 'systemConfig.msgConfig.hasMsg',
					data: false
				});

				// 清除自动登录
				uni.removeStorageSync('Automatic_Login')
				uni.reLaunch({
					url: '/pages/login/login',
				});
			},
			CloseSignaIRPopup() { // 关闭 SignaIR 弹窗，将按钮改为测试链接
				this.showSignaIR = false

				setTimeout(() => {
					this.IP_IS_True = false
				}, 300)
			},
			OpenSignaIRPopup() { // 打开 SignalR弹窗时，开机校验规则
				var that = this

				that.$refs.baseForm.setRules(that.rules)
			},
			IPTextFun(rule, value, data, callback) { // 自定义IP地址的自定义校验
				// 校验IP地址格式是否正确
				function validateIP(input) {
					var regex =
						/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;
					return regex.test(input);
				}
				console.log(validateIP(value))
				if (!validateIP(value)) {
					callback('请输入正确的IP地址格式')
				} else {
					callback()
				}
			},
			BlurIPInput() { // 当 IP 输入框内容修改时，判断是否与之前的值相同，不相同，则重新展示测试连接
				var that = this
				if (that.IPModel.IPText != that.$store.getters.SignalR_IP) {
					that.IP_IS_True = false
				}
			},
			SubTextLine() { // 测试连接
				var that = this
				// 调用vuex中存储本地的方法
				that.$store.dispatch('receiceCode', that.IPModel.IPText);
				uni.showToast({
					title: '保存成功'
				});
				//that.$store.getters.SignalR_Connect.stop();
				that.showSignaIR = false;
			},
			SubBtn() { // 确认提交
				var that = this
				this.$refs.baseForm.validate().then(res => {
					console.log('success', res);
					that.SubLoading = true

					// 调用vuex中存储本地的方法
					that.$store.dispatch('receiceCode', that.IPModel.IPText)

					setTimeout(() => {
						that.SubLoading = false
						that.SignalR_Status = true // 连接状态
						that.$store.state.IPModel.SignalR_Status = true // 在 vuex中记录连接状态
						uni.showToast({
							title: '连接成功'
						})

						// 获取存储的
						console.log(that.$store.getters.SignalR_IP)

					}, 1000)

				}).catch(err => {
					console.log('err', err);
				})
			},
			GetUpdate() { // 检查更新
				var that = this;

				const platform = uni.getSystemInfoSync().platform;
				// UpdateSwitch
				// #ifdef APP-PLUS
				if (platform == "android") {

					// 改变值，开启检索 无更新提示
					that.$store.commit('ChangeAndSetStateData', {
						Name1: 'systemConfig.UpdateSwitch',
						data: true,
					});
					MAPPUpdate();
				} else {
					// IOS直接跳转到APPStore
					plus.runtime.openURL(
						'https://apps.apple.com/cn/app/汇创云平台/id6737088415');
				}


				// #endif
			},
		}
	}
</script>

<style lang="scss">
	* {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	.u-popup {
		flex: initial !important;

	}

	.ModalPopupBox {

		.u-popup__content {
			border-radius: 30rpx !important;
		}
	}

	.content {
		background-color: #f8f8f8;
		height: 100vh;
		display: flex;
		flex-direction: column;

		.CellBox {
			flex: 1;
			// padding-top: 10px;
			// overflow: auto;
			padding: 10px 15px;

			.u-cell-group {
				border-radius: 12px;
				box-shadow: 1px 1px 13px -13px #999;
				overflow: hidden;
				background-color: #fff !important;
			}

			.u-cell {
				// background-color: #fff !important;
				position: relative;
			}

			// 给cell框下方加一根浅的线
			.u-cell::after {
				position: absolute;
				box-sizing: border-box;
				content: ' ';
				pointer-events: none;
				right: 16px;
				bottom: 0;
				left: 16px;
				border-bottom: 1px solid #ebedf0;
				-webkit-transform: scaleY(0.5);
				transform: scaleY(0.5);
			}

			// 去除最后一个cell的下划线
			& .u-cell:last-child::after {
				border-bottom: none !important;
			}
		}

		// 按钮的边框线在这里去除
		uni-button:after {
			border: none !important;
		}

		//  退出登录
		.LoginOutBox {
			width: 100%;
			// text-align: center !important;
			margin-top: 50px;

			button {
				width: 90%;
				margin: 0 auto;
				background-color: #d13c3c;
				border: none !important;
				color: #fff;
			}
		}

		.logoutBox {
			width: 100%;
			margin-top: 50px;

			button {
				width: 90%;
				margin: 0 auto;
				background-color: #f08282;
				border: none !important;
				color: #fff;
			}
		}


		//IP地址 
	}

	.popup-content {
		position: relative;
		display: flex;
		flex-direction: column;
		background-color: #fff;
		width: 86vw;
		max-width: 500px;
		padding: 40rpx 20px 30rpx;
		font-size: 12px;
		border-radius: 4px !important;
		overflow: hidden;

		&_close {
			position: absolute;
			top: 0;
			right: 0;
			width: 28px;
			height: 28px;
			font-weight: 600;
		}

		.title {
			font-size: 16px;
			font-weight: 600;
			text-align: center;
		}

		&_desc {
			margin: 24rpx 0;
			text-align: center;
			color: #999;
		}

		.check {
			zoom: .9;
			font-size: 13px;
			color: #999;
		}

		.btnBox {
			margin-top: 20px;

			.u-button {
				width: 44% !important;
			}
		}
	}
</style>